package com.andnux.android.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;

import com.airbridge.ijkplayerlib.widget.AndroidMediaController;
import com.andnux.android.MainApp;
import com.andnux.android.R;
import com.andnux.android.databinding.ItemImageBinding;
import com.bumptech.glide.Glide;

import tv.danmaku.ijk.media.player.IMediaPlayer;

public class PhotoAdapter extends BaseAdapter<String, ItemImageBinding> {

    private ItemImageBinding itemImageBinding;

    @Override
    public void onBindView(ItemImageBinding itemImageBinding, String s, int position, long id) {
        super.onBindView(itemImageBinding, s, position, id);
        this.itemImageBinding = itemImageBinding;
        ImageView image = itemImageBinding.image;
        if ("-".equalsIgnoreCase(s)) {
            image.setImageResource(R.drawable.ic_baseline_add_24);
        } else {
            SharedPreferences preferences = MainApp.getApp().getSharedPreferences("config", Context.MODE_PRIVATE);
            String url = preferences.getString("url", "");
            if (s.toLowerCase().endsWith(".jpg") || s.toLowerCase().endsWith(".png")
                    || s.toLowerCase().endsWith(".bmp") || s.toLowerCase().endsWith(".webp")) {
                itemImageBinding.image.setVisibility(View.VISIBLE);
                itemImageBinding.video.setVisibility(View.GONE);
                Context context = itemImageBinding.getRoot().getContext();
                Glide.with(context).load("http://" + url + ":8080/design-cloud/file/download?path=" + s).into(image);
            } else if (s.toLowerCase().endsWith(".mp4") || s.toLowerCase().endsWith(".avi")) {
                itemImageBinding.image.setVisibility(View.GONE);
                itemImageBinding.video.setVisibility(View.VISIBLE);
                AndroidMediaController mediaController = new AndroidMediaController(itemImageBinding.video.getContext());
                itemImageBinding.video.setMediaController(mediaController);
                mediaController.setMediaPlayer(itemImageBinding.video);
                itemImageBinding.video.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(IMediaPlayer iMediaPlayer) {
                        itemImageBinding.video.start();
                    }
                });
                itemImageBinding.video.setVideoURI(Uri.parse("http://" + url + ":8080/design-cloud/file/download?path="
                        + s.replaceAll("\\\\", "/")));
                itemImageBinding.video.requestFocus();
            }
        }
    }

    public void stop() {
        if (itemImageBinding.video.isPlaying()) {
            itemImageBinding.video.stopPlayback();
        }
    }
}
